<template>
  <div class="updatePhoto">
    <img class="image" :src="image" ref="image" />
    <van-nav-bar
      class="toolbar"
      left-text="取消"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
import { updateUserPhoto } from "../api/user.js";
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
export default {
  name: "updatePhoto",
  data() {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null //裁切器实例
    };
  },
  props: {
    file: {
      //   type: Object,
      required: true
    }
  },
  methods: {
    // 上传裁剪图片
    getCroppedCanvas() {
      // 包装成promise，虽然他不支持promise
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob(file => {
          resolve(file);
        });
      });
    },
    async onConfirm() {
      this.$toast.loading({
        message: "保存中",
        forbidclick: true,
        duration: 0 //展示时间,0表示持续展示
      });

      const file = await this.getCroppedCanvas();
      const fd = new FormData();
      fd.append("photo", file);

      //   要求提交content-type，提交fromData数据对象，专门用于文件上传的 不能提交{}
      //   const fd = new FormData();
      //   这个是传的参数，是一个对象所以父级不能传一个图片过来
      //   fd.append("photo", this.file);
      await updateUserPhoto(fd);
      this.$toast.success("保存成功");

      //   更新父组件中的头像  传裁切后的图片，用dom解析出来，因为是一个对象
      this.$emit("updatePhoto", window.URL.createObjectURL(file));

      //   关闭弹出层
      this.$emit("close");
    }
  },
  mounted() {
    //   获取需要裁切的图片dom
    const image = this.$refs.image;

    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    });
    console.log(this.cropper);
  }
};
</script>
<style scoped lang="less">
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}
.image {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
</style>
